#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <errno.h>


typedef void (* fun_t)();


#define NUM 5
//函数指针数组
fun_t handers[NUM+1];


void DownLoad()
{
    printf("这是一个下载任务\n");
}

void Flush()

{
    printf("这是一个刷新任务\n");
}
void Others()
{
    printf("这是一个其它任务\n");
}

void RegisterHander(fun_t handers[],fun_t fun)
{
    int i = 0;
    for(;i < NUM;i++)
    {
        if(handers[i] == NULL)
            break;
    }
    //判断数组是否满
    if(i == NUM)
        return;
    //没有满，添加进去
    handers[i++] = fun;
    handers[i] = NULL;
}






int main()
{

    //注册任务
    RegisterHander(handers,DownLoad);
    RegisterHander(handers,Flush);
    RegisterHander(handers,Others);
    pid_t id = fork();

    if(id == 0)
    {
        //子进程
        int cnt = 3;
        while(cnt--)
        {
            printf("我是子进程，pid:%d,ppid:%d\n",getpid(),getppid());
            sleep(1);
            //int *p = NULL;
            // *p = 999;
            //int a = 10;
            //a/=0;
        }
            exit(10);
    }
    //父进程
    
    int status;
    while(1)
    {
        pid_t rid = waitpid(id,&status,WNOHANG);
 
        if(rid > 0)
        {  
            printf("Wait Success! rid:%d,exit code:%d,exit signal:%d\n",rid,(status>>8)&0xFF,status&0x7F);    
            break;
        }
        else if(rid == 0)
        {
            handers[0]();
            handers[1]();
            handers[2]();
            printf("本轮调用结束，子进程没有退出！\n");
        }
        else 
        {
            printf("等待失败!\n");
            break;
        }

        sleep(1);


    }
    
    
    
    
  
    
    
    
    
    
    
    

    
    
    
    
    //sleep(5);
    ////pid_t rid = wait(NULL);
    ////pid_t rid = waitpid(-1,NULL,0);
    //int status = 0;
    //pid_t rid = waitpid(id,&status,0);
    //if(rid > 0)
    //{
    //    printf("Wait Success! rid:%d,exit code:%d,exit signal:%d\n",rid,(status>>8)&0xFF,status&0x7F);

    //}
    //else 
    //{
    //    printf("Wait Failed! %d:%s\n",errno,strerror(errno));
    //}
    //


    return 0;
}
